<template>
  <div class="calendar-page">
    <el-calendar v-model="current">
      <template #date-cell="{ data }">
        <div class="day-cell" :class="cellClass(data.day)" @click="openEditOrAdd(data.day)">
          <div class="date-text">{{ Number(data.day.slice(-2)) }}</div>
          <div class="badges">
            <el-tag v-if="isOvertime(data.day)" size="small" type="danger" effect="dark">加班</el-tag>
            <el-tag v-if="holidayLabel(data.day)" size="small" type="warning" effect="dark">{{ holidayLabel(data.day) }}</el-tag>
          </div>
        </div>
      </template>
    </el-calendar>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑日历' : '新增日历'" width="420px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="日期">
          <el-date-picker v-model="form.calendarDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="是否加班">
          <el-switch v-model="form.isUrgentWorkday" />
        </el-form-item>
        <el-form-item label="节假日类型">
          <el-input v-model="form.hoildayType" placeholder="如：国庆" />
        </el-form-item>
        <el-form-item label="加班原因">
          <el-input v-model="form.urgentReason" placeholder="可选" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="save">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, watch } from 'vue'
import { getReadClient, getWriteClient } from '@/Urls/AxiosHelper'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'

const route = useRoute()
const current = ref<Date>(new Date())
const tableData = ref<any[]>([])
const schedread = getReadClient(1)

const dialogVisible = ref(false)
const saving = ref(false)
const isEdit = ref(false)
const editingKey = ref<string>('')
const editingId = ref<string | number | null>(null)
const form = ref({
  calendarDate: '',
  isUrgentWorkday: false,
  hoildayType: '',
  urgentReason: '',
})

function openEditOrAdd(dayKey: string){
  const it = byDate.value[dayKey]
  if (it){
    // 编辑：反填 + 记录 id
    isEdit.value = true
    editingKey.value = dayKey
    editingId.value = it?.id ?? it?.Id ?? it?.calendarId ?? it?.CalendarId ?? it?.calenderId ?? it?.CalenderId ?? null
    form.value.calendarDate = dayKey
    form.value.isUrgentWorkday = it?.isUrgentWorkday ?? it?.IsUrgentWorkday ?? false
    form.value.hoildayType = it?.hoildayType ?? it?.holidayType ?? it?.HolidayType ?? ''
    form.value.urgentReason = it?.urgentReason ?? ''
  }else{
    // 新增
    isEdit.value = false
    editingKey.value = dayKey
    editingId.value = null
    form.value.calendarDate = dayKey
    form.value.isUrgentWorkday = false
    form.value.hoildayType = ''
    form.value.urgentReason = ''
  }
  dialogVisible.value = true
}

function toDateKey(val: any): string | null{
  if (val == null) return null
  if (typeof val === 'number'){
    const d = new Date(val)
    if (!isNaN(d.getTime())){
      const y = d.getFullYear()
      const m = `${d.getMonth()+1}`.padStart(2,'0')
      const day = `${d.getDate()}`.padStart(2,'0')
      return `${y}-${m}-${day}`
    }
    return null
  }
  if (typeof val === 'string'){
    const s = val.replace(/\//g,'-').trim()
    if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return s
    if (/^\d{4}-\d{2}-\d{2}[ T]/.test(s)) return s.slice(0,10)
    const d = new Date(s)
    if (!isNaN(d.getTime())){
      const y = d.getFullYear()
      const m = `${d.getMonth()+1}`.padStart(2,'0')
      const day = `${d.getDate()}`.padStart(2,'0')
      return `${y}-${m}-${day}`
    }
  }
  return null
}

const byDate = computed<Record<string, any>>(()=>{
  const map: Record<string, any> = {}
  for(const it of tableData.value){
    const key = toDateKey(it?.calendarDate)
    if(key) map[key] = it
  }
  return map
})

function coerceBool(v: any): boolean{
  if (typeof v === 'boolean') return v
  if (typeof v === 'number') return v === 1
  if (typeof v === 'string'){
    const t = v.trim().toLowerCase()
    return t === 'true' || t === '1' || t === 'y'
  }
  return false
}

function isOvertime(dayKey: string): boolean{
  const it = byDate.value[dayKey]
  return coerceBool(it?.isUrgentWorkday ?? it?.IsUrgentWorkday)
}

function isHoliday(dayKey: string): boolean{
  const it = byDate.value[dayKey]
  const val = it?.hoildayType ?? it?.holidayType ?? it?.HolidayType
  return val !== undefined && val !== null && String(val).trim() !== ''
}

function holidayLabel(dayKey: string): string{
  const it = byDate.value[dayKey]
  const val = it?.hoildayType ?? it?.holidayType ?? it?.HolidayType
  return val ? String(val) : ''
}

function cellClass(dayKey: string){
  return {
    isOvertime: isOvertime(dayKey),
    isHoliday: !isOvertime(dayKey) && isHoliday(dayKey),
  }
}

const schedShow = ()=>{
  schedread({ url:'schedread/api/Calendar/GetList/list', method:'get' })
    .then(res=>{ 
      tableData.value = res?.data?.data ?? []
      const first = tableData.value?.[0]
      const key = toDateKey(first?.calendarDate)
      if (key){
        const d = new Date(key)
        if (!isNaN(d.getTime())) current.value = d
      }
    })
}

const calendwrite = getWriteClient(1)
async function save(){
  if(!form.value.calendarDate){
    ElMessage.error('请选择日期');
    return
  }
  saving.value = true
  try{
    if (isEdit.value){
      await calendwrite.post('schedwrite/api/Team/UpdCalender', {
        id: editingId.value,
        calendarId: editingId.value,
        calendarDate: form.value.calendarDate,
        isUrgentWorkday: form.value.isUrgentWorkday,
        hoildayType: form.value.hoildayType,
        urgentReason: form.value.urgentReason,
      })
      ElMessage.success('修改成功')
    }else{
      await calendwrite.post('schedwrite/api/Team/AddCalender', {
        calendarDate: form.value.calendarDate,
        isUrgentWorkday: form.value.isUrgentWorkday,
        hoildayType: form.value.hoildayType,
        urgentReason: form.value.urgentReason,
      })
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    schedShow()
  }catch(e:any){
    ElMessage.error(e?.message || (isEdit.value ? '修改失败' : '添加失败'))
  }finally{
    saving.value = false
  }
}

// 初始化：优先使用路由中的 month 或已保存的月份
function initMonth(){
  const q = String(route.query.month || '').trim()
  const saved = localStorage.getItem('sched-current-month') || ''
  const val = q || saved
  if(/^\d{4}-\d{2}$/.test(val)){
    const [y,m] = val.split('-').map(n=> Number(n))
    const d = new Date(y, m-1, 1)
    if(!isNaN(d.getTime())) current.value = d
  }
}

watch(()=> route.query.month, (nv)=>{
  const val = String(nv || '')
  if(/^\d{4}-\d{2}$/.test(val)){
    const [y,m] = val.split('-').map(n=> Number(n))
    const d = new Date(y, m-1, 1)
    if(!isNaN(d.getTime())) current.value = d
  }
})

onMounted(()=>{ initMonth(); schedShow() })
</script>

<style scoped>
.calendar-page{ display:flex; flex-direction:column; gap:12px; }
:deep(.el-calendar-day){ padding: 0; }
.day-cell{ position:relative; min-height:68px; padding:6px; border-radius:6px; height:100%; box-sizing:border-box; cursor: pointer; }
.day-cell.isHoliday{ background:#fff2b8; }
.day-cell.isOvertime{ background:#ffd6d6; }
.date-text{ font-weight:600; }
.badges{ margin-top:6px; display:flex; gap:6px; flex-wrap:wrap; }
</style>
